﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Thksoft.ParameterSettings
{
    public partial class ProjectSetting : BaseUI.BasePage
    {
        public static string PROID = "0";
        private QS_PROJECT_CODEBLL procodeBLL = new QS_PROJECT_CODEBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCompany();
                BindPro();

                ViewState["SortOrder"] = "n_proid";
                ViewState["OrderDire"] = " asc ";
                //初始化绑定数据
                //BindProjectName(false);
            }
        }

        /// <summary>
        /// 绑定公司
        /// </summary>
        private void BindCompany()
        {
            DataTable tableOrganization = new Sys_CompanyBLL().SelectByWhere("", lognUser.USER_COMPANY.ToString());
            if (tableOrganization != null && tableOrganization.Rows.Count > 0)
            {
                // setList(tableOrganization, ddlCompany);
                PublicMethod.BindDDL(ddlCompany1, tableOrganization, "CMY_ID", "CMY_NAME", false);

                ddlCompany1.Items.Insert(0, new ListItem("通用", "0"));

                ddlCompany1.SelectedValue = "0";
            }
            else
            {
                ddlCompany1.Items.Add(new ListItem("无", "0"));
            }
        }

        /// <summary>
        /// 绑定父级项目
        /// </summary>
        public void BindPro()
        {
            DataTable dt = new QS_PROJECTBLL().SelectBy(" and CMY_ID=" + ddlCompany1.SelectedValue);

            ddlParentPro.Items.Clear();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["N_PARENTID"].ToString() == "0")
                {
                    ListItem it = new ListItem(dt.Rows[i]["c_proname"].ToString(), dt.Rows[i]["N_PROID"].ToString());
                    ddlParentPro.Items.Add(it);
                    BindNextNodes(dt.Rows[i]["N_PROID"].ToString(), dt);
                }
            }

            ddlParentPro.Items.Insert(0, new ListItem("--根节点--", "0"));
            ddlParentPro.SelectedValue = "0";
        }

        public void BindNextNodes(string NodeId, DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["N_PARENTID"].ToString() == NodeId)
                {
                    ListItem it = new ListItem(dt.Rows[i]["c_proname"].ToString(), dt.Rows[i]["N_PROID"].ToString());

                    ddlParentPro.Items.Add(it);

                    BindNextNodes(dt.Rows[i]["N_PROID"].ToString(), dt);
                }
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(hidKey.Value))
            {
                if (this.hidKey.Value == "0")
                {
                    //this.myProject.Visible = true;

                    //string proId = this.hidProID.Value.ToString();
                    //DataTable dt = new Qs_FundMonPlanBLL().SelectByProId(proId);
                    //if (dt != null && dt.Rows.Count > 0)
                    //{
                    //    this.TextBoxFatherProjectName.Text = dt.Rows[0]["pro_name"].ToString();
                    //    this.hidFatherId.Value = proId;
                    //}

                    BindProjectName(false); //重新绑定数据
                }
                else
                {
                    //this.myProject.Visible = false;

                    BindProjectName(false);
                }
            }
        }

        /// <summary>
        /// 绑定项目名称（非动态）绑定GridView
        /// </summary>
        public void BindProjectName(bool iSsort)
        {
            string proId = this.hidProID.Value.ToString() == "" ? "" : this.hidProID.Value.ToString();

            #region 郑钰川新增自定义关键字

            PROID = proId;

            DataTable dt_procode = procodeBLL.Select(" AND N_PROID = " + proId);

            if (dt_procode == null || dt_procode.Rows.Count == 0)
            {
                FORM_CODE_STRING.Text = "请选择关键字";
            }
            else
            {
                string codeText = "";
                foreach (DataRow dr in dt_procode.Rows)
                {
                    codeText += dr["C_CODE"].ToString() + ",";
                }
                FORM_CODE_STRING.Text = codeText.Substring(0, codeText.Length - 1);
            }

            #endregion 郑钰川新增自定义关键字

            string whr = @" and  t.n_proid in
       (select d.n_proid
          from qs_project d
         start with d.n_proid = " + proId + @"
        connect by prior d.n_proid = d.N_PARENTID)";

            DataTable dt = new QS_PROJECTBLL().SelectBy(whr);

            DataView view = dt.DefaultView;

            if (iSsort)
            {
                string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
                view.Sort = sort;//设置排序
            }

            GvProject.DataSource = view;

            GvProject.DataBind();
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            //新增
            if (txtName.Text.Trim() == "")
            {
                MessageBox.Show(Page, "请输入项目名称！");
                return;
            }
            if (FORM_PRO_NUMBER.Text.Trim() == "")
            {
                MessageBox.Show(Page, "请输入项目编号！");
                return;
            }

            int num = 0;

            if (TextBox1.Text.Trim() != "")
            {
                if (!int.TryParse(TextBox1.Text.Trim(), out num))
                {
                    MessageBox.Show(Page, "顺序1请输入数字！");
                    return;
                }
            }
            int num2 = 0;

            if (TextBox2.Text.Trim() != "")
            {
                if (!int.TryParse(TextBox2.Text.Trim(), out num2))
                {
                    MessageBox.Show(Page, "顺序2请输入数字！");
                    return;
                }
            }

            string C_PRONUM = FORM_PRO_NUMBER.Text.TrimEnd();
            string C_PRONAME = txtName.Text.TrimEnd();
            string sqls = string.Format("SELECT * FROM QS_PROJECT WHERE CMY_ID=" + ddlCompany1.SelectedValue + @" and (C_PRONUM=" + C_PRONUM + " OR C_PRONAME='" + C_PRONAME + "')");

            int cot = new QS_PROJECTBLL().SqlCount(sqls);
            if (cot > 0)
            {
                MessageBox.Show(Page, "不能添加同一项目名称或项目编号的数据！");
                return;
            }

            QS_PROJECT model = new QS_PROJECT
            {
                N_PROID = 0,
                C_PRONAME = txtName.Text.TrimEnd(),
                N_OPERATORID = CurrentUserID,
                D_DATE = DateTime.Now,
                N_PARENTID = decimal.Parse(ddlParentPro.SelectedValue),
                C_REMARK = txtGLRY.Text.TrimEnd(),
                N_NUM1 = num,
                N_NUM2 = num2,
                N_STATE = decimal.Parse(ddlState.SelectedValue),
                N_TYPE = decimal.Parse(DropDownList1.SelectedValue),
                C_PRONUM = FORM_PRO_NUMBER.Text.TrimEnd(),
                CMY_ID = decimal.Parse(ddlCompany1.SelectedValue),
                N_TYPE2 = decimal.Parse(FORM_TYPE2.SelectedValue),
                C_CODE1 = txtGj1.Text.Trim(),
                C_CODE2 = txtGj2.Text.Trim(),
                C_CODE3 = txtGj3.Text.Trim(),
                C_CODE4 = txtGj4.Text.Trim()
            };
            int count = new QS_PROJECTBLL().insert(model, "项目设置", lognUser.USER_NAME);

            if (count > 0)
            {
                MessageBox.Show(Page, "新增成功！");
                BindClear();
                BindProjectName(false);
            }
            else
            {
                MessageBox.Show(Page, "新增失败！");
                return;
            }
        }

        private void BindClear()
        {
            txtName.Text = "";
            txtGLRY.Text = "";
            TextBox1.Text = "";
            TextBox2.Text = "";
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (hidProidUp.Value == "")
            {
                MessageBox.Show(Page, "请先选择修改行！");
                return;
            }
            //新增
            int num = 0;

            if (TextBox1.Text.Trim() != "")
            {
                if (!int.TryParse(TextBox1.Text.Trim(), out num))
                {
                    MessageBox.Show(Page, "顺序1请输入数字！");
                    return;
                }
            }
            int num2 = 0;

            if (TextBox2.Text.Trim() != "")
            {
                if (!int.TryParse(TextBox2.Text.Trim(), out num2))
                {
                    MessageBox.Show(Page, "顺序2请输入数字！");
                    return;
                }
            }
            QS_PROJECT model = new QS_PROJECT
            {
                N_PROID = decimal.Parse(hidProidUp.Value),
                C_PRONAME = txtName.Text.TrimEnd(),
                N_OPERATORID = CurrentUserID,
                D_DATE = DateTime.Now,
                N_PARENTID = decimal.Parse(ddlParentPro.SelectedValue),
                C_REMARK = txtGLRY.Text.TrimEnd(),
                N_NUM1 = num,
                N_NUM2 = num2,
                N_STATE = decimal.Parse(ddlState.SelectedValue),
                N_TYPE = decimal.Parse(DropDownList1.SelectedValue),
                C_PRONUM = FORM_PRO_NUMBER.Text.TrimEnd(),
                CMY_ID = decimal.Parse(ddlCompany1.SelectedValue),
                N_TYPE2 = decimal.Parse(FORM_TYPE2.SelectedValue),
                C_CODE1 = txtGj1.Text.Trim(),
                C_CODE2 = txtGj2.Text.Trim(),
                C_CODE3 = txtGj3.Text.Trim(),
                C_CODE4 = txtGj4.Text.Trim()
            };
            int count = new QS_PROJECTBLL().Update(model, "项目设置", lognUser.USER_NAME);

            if (count > 0)
            {
                MessageBox.Show(Page, "修改成功！");
                BindClear();
                BindProjectName(false);
            }
            else
            {
                MessageBox.Show(Page, "修改失败！");
                return;
            }
        }

        protected void GvProject_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;

            if (ViewState["SortOrder"].ToString() == sPage)
            {
                if (ViewState["OrderDire"].ToString() == "Desc")
                    ViewState["OrderDire"] = "ASC";
                else
                    ViewState["OrderDire"] = "Desc";
            }
            else
            {
                ViewState["SortOrder"] = e.SortExpression;
                ViewState["OrderDire"] = "ASC";
            }

            BindProjectName(true);
        }

        /// <summary>
        /// Render
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            foreach (GridViewRow row in GvProject.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    row.Attributes["onclick"] = ClientScript.GetPostBackEventReference(GvProject, "Select$" + row.RowIndex.ToString(), true);
                    row.Attributes["style"] = "cursor:pointer;table-layout:fixed";
                    row.Attributes["title"] = "单击选择行";
                }
            }

            base.Render(writer);
        }

        protected void GvProject_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            string id = this.GvProject.Rows[e.NewSelectedIndex].Cells[0].Text.ToString();

            QS_PROJECT model = new QS_PROJECTBLL().GetModelById(id);

            ddlCompany1.SelectedValue = model.CMY_ID.ToString();

            BindPro();
            hidProidUp.Value = model.N_PROID.ToString();
            txtName.Text = model.C_PRONAME;
            ddlParentPro.SelectedValue = model.N_PARENTID.ToString();
            ddlState.SelectedValue = model.N_STATE.ToString();
            TextBox1.Text = model.N_NUM1.ToString();
            TextBox2.Text = model.N_NUM2.ToString();
            txtGLRY.Text = model.C_REMARK;
            DropDownList1.SelectedValue = model.N_TYPE.ToString();
            FORM_PRO_NUMBER.Text = model.C_PRONUM == null ? "" : model.C_PRONUM;
            FORM_TYPE2.SelectedValue = model.N_TYPE2.ToString();
            txtGj1.Text = model.C_CODE1;
            txtGj2.Text = model.C_CODE2;
            txtGj3.Text = model.C_CODE3;
            txtGj4.Text = model.C_CODE4;
        }

        protected void ddlCompany1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindPro();
        }
    }
}